<template>
  <el-dialog :append-to-body="true" :close-on-click-modal="false" :before-close="cancel" :visible.sync="dialog" title="流程导入" width="500px">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
      <!--   上传文件   -->
      <el-form-item label="上传">
        <el-upload
          ref="upload"
          :limit="1"
          :before-upload="beforeUpload"
          :auto-upload="false"
          :headers="headers"
          accept=".bpmn,.xml"
          :on-success="handleSuccess"
          :on-error="handleError"
          :action="fileUploadPath">
          <div class="eladmin-upload"><i class="el-icon-upload"/> 添加文件</div>
          <div slot="tip" class="el-upload__tip">请上传BPMN或XML文件，且不超过100M</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      loading: false, dialog: false,
      headers: { 'Authorization': 'Bearer ' + getToken() },
      fileUploadPath: process.env.BASE_API + '/flowProcess/deploy',
      form: {
        id: '',
        name: ''
      },
      rules: {
      }
    }
  },
  methods: {
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.$refs.upload.submit()
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
    },
    beforeUpload(file) {
      this.loading = true
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      const startIndex = file.name.lastIndexOf(".");
      if(startIndex !== -1){
        const suffix=file.name.substring(startIndex+1, file.name.length).toLowerCase();
        if(suffix!=='bpmn' &&  suffix!=='xml'){
          this.$message.error('请上传BPMN或XML文件!')
          this.loading = false
          return false
        }
      }
      this.loading = false
      return isLt2M
    },
    handleSuccess(response, file, fileList) {
      this.dialog = false
      this.resetForm()
      this.$refs.upload.clearFiles()
      this.$parent.init()
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    }
  }
}
</script>

<style scoped>

</style>
